const cartListEle = document.querySelector('#cartList')
const totalEle = document.querySelector('#total>div')
let checkAll = false
// 动态渲染界面
function loadProduct() {
    // 获取localStorage里面存的东西
    let list = localStorage.getItem('MYCART')
    list = JSON.parse(list) || []
    let str = ` <div class="title">
                    <div class="checkAll"><input type="checkbox" name="checkAll" ${checkAll?'checked':''}>全选</div>
                    <div class="product">商品</div>
                    <div class="price">单价</div>
                    <div class="num">数量</div>
                    <div class="subtotal">小计</div>
                    <div class="orperation">操作</div>
                </div>`
    list.forEach(item => {
        let newStr = `<div class="list" data-id="${item.id}">
                            <div class="check"><input type="checkbox" name="check" ${item.state?'checked':''}></div>
                            <div class="product">
                                <img src="${item.picture}" alt="" class="productcheck">
                                <p class="productcheck">${item.product}</p>
                            </div>
                            <div class="price">￥${item.price}</div>
                            <div class="num">
                                <input type="button" name="minus" value="-" ${item.num<=0?'disabled':''}><input type="text" name="count" value="${item.num}"><input type="button"
                                    name="plus" value="+">
                            </div>
                            <div class="subtotal">￥${item.singlePrice}</div>
                            <div class="orperation">
                                <a href="#" class="del">删除</a>
                                <a href="#">收藏</a>
                            </div>
                        </div>`
        str += newStr
    });
    cartListEle.innerHTML = str

    // let operateCart = new OperateCart('#cartList')
    // operateCart.onMinus()
}
loadProduct()
// 动态操作购物车列表
// 面向对象写不来
/* class OperateCart {
    constructor(id) {
        this.root = document.querySelector(id)
        this.minus = document.querySelector('.minus')
        console.log(this.root);
        console.log(this.minus);
    }
    // -
    
    onMinus() {
        this.minus.onclick = () => {
            this.nextElementSibling.value++
        }
    }
} */
function operateCart() {
    let cartlist = document.querySelector('#cartList')
    cartlist.addEventListener('click', function (e) {
        e = e || window.event
        let target = e.target || e.srcElement
        e.preventDefault()
        let list = localStorage.getItem('MYCART')
        list = JSON.parse(list) || []
        // +
        if (target.getAttribute('name') == 'plus') {
            let id = target.parentNode.parentNode.getAttribute('data-id')
            let product = list.find(item => item.id == id)
            product.num++
            product.singlePrice = (product.num * product.price).toFixed(2)
            localStorage.setItem('MYCART', JSON.stringify(list))
            loadProduct()
        }
        // -
        if (target.value == '-') {
            let id = target.parentNode.parentNode.getAttribute('data-id')
            let product = list.find(item => item.id == id)
            product.num--
            product.singlePrice = (product.num * product.price).toFixed(2)
            localStorage.setItem('MYCART', JSON.stringify(list))
            loadProduct()
        }
        // 删除
        if (target.getAttribute('class') == 'del') {
            let id = target.parentNode.parentNode.getAttribute('data-id')
            let index = list.findIndex(item => item.id == id)
            list.splice(index, 1)
            localStorage.setItem('MYCART', JSON.stringify(list))
            loadProduct()
        }
        // 全选
        if (target.getAttribute('name') == 'checkAll') {
            checkAll = !checkAll
            list.forEach(item => item.state = checkAll)
            localStorage.setItem('MYCART', JSON.stringify(list))
            localStorage.setItem('MYSTATE', JSON.stringify(checkAll))
            loadProduct()
            let checkedList = list.filter(item => item.state == true)
            onTotal(checkedList)
        }
        // 复选
        if (target.getAttribute('name') == 'check') {
            let id = target.parentNode.parentNode.getAttribute('data-id')
            let product = list.find(item => item.id == id)
            product.state = !product.state
            // 如果所有复选框都选中了，就把全选选上
            checkAll = list.every(item => item.state == true)
            localStorage.setItem('MYCART', JSON.stringify(list))
            localStorage.setItem('MYSTATE', JSON.stringify(checkAll))
            loadProduct()
            let checkedList = list.filter(item => item.state == true)
            onTotal(checkedList)
        }
        // 点击商品跳转到商品详情页
        console.log(target);
        if (target.getAttribute('class') == 'productcheck') {
            let id = target.parentNode.parentNode.getAttribute('data-id')
            location.href = 'productDetail.html?id=' + id
        }
    })
}
operateCart()
// 计算总计
function onTotal(list) {
    let total = list.reduce((sum, item) => sum += parseFloat(item.singlePrice), 0)
    total = total.toFixed(2)
    totalEle.innerHTML = `<p>商品总价:<span class="totalPrice">￥${total}</span></p>`
}
// 点击logo回到首页
function toIndex() {
    const logoEle = document.querySelector('#header img')
    logoEle.onclick = function () {
        location.href = 'index.html'
    }
}
toIndex()